package com.zw.mes.module.prodtaskmanager.controller;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.zw.mes.base.BaseController;
import com.zw.mes.common.JsonResult;
import com.zw.mes.module.prodtaskmanager.entity.ProdOrd;
import com.zw.mes.module.prodtaskmanager.entity.VwPreEnquiryFile;
import com.zw.mes.module.prodtaskmanager.entity.VwProject;
import com.zw.mes.module.prodtaskmanager.model.*;
import com.zw.mes.module.prodtaskmanager.service.ProdOrdService;
import com.zw.mes.module.system.service.LogService;
import com.zw.mes.util.*;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author 徐一贺
 * @className ProdOrdController
 * @description 生产令控制层
 * @date 2021/1/11 15:52
 * @versron ver 1.0
 */
@Controller
@RequestMapping("/prodOrd")
public class ProdOrdController extends BaseController {


  private ProdOrdService prodOrdService;

  @Autowired
  public void setProdOrdService(ProdOrdService prodOrdService) {
    this.prodOrdService = prodOrdService;
  }

  private LogService logService;

  @Autowired
  public void setLogService(LogService logService) {
    this.logService = logService;
  }

  @Value("${user.upload.path}")
  private String uploadPath;

  /**
   * page 跳转到生产令下达列表页
   *
   * @param
   * @return java.lang.String
   * @author 徐一贺
   * @date 2021/1/13 16:36
   */
  @GetMapping
  @RequiresPermissions("pro:release:view")
  public String page() {
    return "prodTaskManager/prodOrderRelease/page";
  }

  /**
   * changeQuery 跳转到生产令表更查询页
   *
   * @return java.lang.String
   * @author 徐一贺
   * @date 2021/2/23 10:56
   */
  @GetMapping("/changeQuery")
  @RequiresPermissions("pro:orderChange:view")
  public String changeQuery() {
    return "prodTaskManager/prodOrderChangeQuery/page";
  }

  /**
   * prodReleaseList 生产令任务下达页列表
   *
   * @param param 搜索参数
   * @return com.zw.mes.common.JsonResult
   * @author 徐一贺
   * @date 2021/1/14 8:06
   */
  @ResponseBody
  @PostMapping("/prodReleaseList")
  @RequiresPermissions("pro:release:view")
  public JsonResult prodReleaseList(ProdOrdModel param) {
    startPage();
    return jsonResult(prodOrdService.prodReleaseList(param));
  }

  /**
   * changeQueryList 生产令变更记录查询
   *
   * @param param 搜索参数
   * @return com.zw.mes.common.JsonResult
   * @author 徐一贺
   * @date 2021/2/23 11:22
   */
  @ResponseBody
  @PostMapping("/changeQuery/list")
  @RequiresPermissions("pro:orderChange:view")
  public JsonResult changeQueryList(ProdOrdChaModel param) {
    startPage();
    return jsonResult(prodOrdService.findChangeQueryList(param));
  }

  /**
   * stopProd 终止生产令
   *
   * @param param 终止信息
   * @return com.zw.mes.common.JsonResult
   * @author 徐一贺
   * @date 2021/2/3 10:55
   */
  @ResponseBody
  @PostMapping("/stopProd")
  @RequiresPermissions("pro:release:end")
  public JsonResult stopProd(ProdOrdModel param) {
    return prodOrdService.stopProd(param);
  }

  /**
   * @methodName: postponementProdOrd
   * @description: 生产令暂缓
   * @param: param 暂缓参数
   * @return： com.zw.mes.common.JsonResult
   * @exception：
   * @author： 徐一贺
   * @date： 2021/3/23 12:37
   * @office: 智能控制设计科
   * @research institute： 智能控制设计所
   * @department： 机械设计院
   * @company: 辽宁忠旺机械设备制造有限公司
   * @group： 忠旺集团
   * @version: 1.0
   */
  @ResponseBody
  @PostMapping("/postponementProdOrd")
  @RequiresPermissions("pro:release:end")
  public JsonResult postponementProdOrd(ProdOrdModel param) {
    return prodOrdService.postponementProdOrd(param);
  }

//  /**
//   * @methodName: cancelPostponement
//   * @description: 取消暂缓
//   * @param: param
//   * @return： com.zw.mes.common.JsonResult
//   * @exception：
//   * @author： 徐一贺
//   * @date： 2021/3/23 13:09
//   * @office: 智能控制设计科
//   * @research institute： 智能控制设计所
//   * @department： 机械设计院
//   * @company: 辽宁忠旺机械设备制造有限公司
//   * @group： 忠旺集团
//   * @version: 1.0
//   */
//  @ResponseBody
//  @PostMapping("/cancelPostponement")
//  @RequiresPermissions("pro:release:postponement")
//  public JsonResult cancelPostponement(ProdOrdModel param) {
//    return prodOrdService.cancelPostponement(param);
//  }

  /**
   * getProInfo 通过项目表主键获取项目信息
   *
   * @param proId 项目表主键
   * @return com.zw.mes.common.JsonResult
   * @author 徐一贺
   * @date 2021/1/14 8:59
   */
  @ResponseBody
  @PostMapping("/getProInfo")
  @RequiresPermissions(value = {"pro:release:edit"},logical = Logical.OR)
  public JsonResult getProInfo(Integer proId) {
    return success().setData(prodOrdService.getProInfo(proId));
  }

  /** 保存生产令变更 */
  @ResponseBody
  @PostMapping("/saveChange")
  @RequiresPermissions("pro:release:commit")
  public JsonResult saveChange(
      HttpServletRequest httpServletRequest, String prodJson, String removeJson) throws Exception {
    String clientIp = IpUtil.getIpAddr(httpServletRequest);
    Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
    List<ProdOrdJsonModel> prodOrds =
        gson.fromJson(prodJson, new TypeToken<List<ProdOrdJsonModel>>() {}.getType());
    List<ProdOrdModel> dataList = new ArrayList<>();
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date current = new Date();
    for (int i = 0; i < prodOrds.size(); i++) {
      ProdOrdModel dataModel = new ProdOrdModel();
      if (prodOrds.get(i).getProdId() == null) {
        dataModel.setProdId(prodOrds.get(i).getProdId());
        dataModel.setProdNo(prodOrds.get(i).getProdNo());
        dataModel.setProdNum(prodOrds.get(i).getProdNum());
        dataModel.setProdRem(prodOrds.get(i).getProdRem());
        dataModel.setProdBacTyp(prodOrds.get(i).getProdBacTyp());
        dataModel.setProdTyp(prodOrds.get(i).getProdTyp());
        dataModel.setProdIsKey(prodOrds.get(i).getProdIsKey());
        dataModel.setProdProCod(prodOrds.get(i).getProdProCod());
        dataModel.setProdCreDat(current);
        if(prodOrds.get(i).getProdDelDat()!=null){
          dataModel.setProdDelDat(format.parse(prodOrds.get(i).getProdDelDat()+" "+new SimpleDateFormat("HH:mm:ss").format(current)));
        }else{
          dataModel.setProdDelDat(null);
        }
        dataModel.setProdCreUid(ShiroUtils.getUserId());
        dataModel.setProdIsDel((byte) 0);
        dataModel.setProdSta(1);
        dataModel.setProdIsIni((byte) 0);
        dataModel.setProdManSta(1);
        dataModel.setChangeReason(prodOrds.get(i).getChangeReason());
        dataModel.setOs(prodOrds.get(i).getOs());
        dataModel.setBrowser(prodOrds.get(i).getBrowser());
      } else {
        dataModel.setProdId(prodOrds.get(i).getProdId());
        dataModel.setProdNo(prodOrds.get(i).getProdNo());
        dataModel.setProdNum(prodOrds.get(i).getProdNum());
        dataModel.setProdRem(prodOrds.get(i).getProdRem());
        dataModel.setProdBacTyp(prodOrds.get(i).getProdBacTyp());
        dataModel.setProdTyp(prodOrds.get(i).getProdTyp());
        dataModel.setProdIsKey(prodOrds.get(i).getProdIsKey());
        dataModel.setProdProCod(prodOrds.get(i).getProdProCod());
        dataModel.setProdDelDat(current);
        if(prodOrds.get(i).getProdDelDat()!=null){
          dataModel.setProdDelDat(format.parse(prodOrds.get(i).getProdDelDat()+" "+new SimpleDateFormat("HH:mm:ss").format(current)));
        }else{
          dataModel.setProdDelDat(null);
        }
        dataModel.setChangeReason(prodOrds.get(i).getChangeReason());
        dataModel.setOs(prodOrds.get(i).getOs());
        dataModel.setBrowser(prodOrds.get(i).getBrowser());
      }
      dataList.add(dataModel);
    }
    return prodOrdService.saveChange(dataList, clientIp);
  }
  /**
   * 保存编辑生产令
   *
   * @param prodJson 生产令信息
   * @author 徐一贺
   * @date 2021/2/21 13:53
   */
  @ResponseBody
  @PostMapping("/saveEdit")
  @RequiresPermissions("pro:release:commit")
  public JsonResult saveEdit(String prodJson, String removeJson) throws Exception {
    Date currentDate = new Date();
    Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
    List<ProdOrdJsonModel> prodOrds =
        gson.fromJson(prodJson, new TypeToken<List<ProdOrdJsonModel>>() {}.getType());
    List<ProdOrdJsonModel> removeProdOrds =
        gson.fromJson(removeJson, new TypeToken<List<ProdOrdJsonModel>>() {}.getType());
    List<ProdOrdModel> dataList = new ArrayList<>();
    for (int i = 0; i < prodOrds.size(); i++) {
      ProdOrdModel dataModel = new ProdOrdModel();
      dataModel.setProdId(prodOrds.get(i).getProdId());
      dataModel.setProdNo(prodOrds.get(i).getProdNo());
      dataModel.setProdNum(prodOrds.get(i).getProdNum());
      dataModel.setProdRem(prodOrds.get(i).getProdRem());
      dataModel.setProdBacTyp(prodOrds.get(i).getProdBacTyp());
      dataModel.setProdTyp(prodOrds.get(i).getProdTyp());
      dataModel.setProdIsKey(prodOrds.get(i).getProdIsKey());
      dataModel.setProdProCod(prodOrds.get(i).getProdProCod());
      SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      dataModel.setProdCreDat(currentDate);
      SimpleDateFormat format2 = new SimpleDateFormat("HH:mm:ss");
      if (prodOrds.get(i).getProdDelDat() != null) {
        dataModel.setProdDelDat(format.parse(prodOrds.get(i).getProdDelDat()+" "+format2.format(currentDate)));
      }
      dataModel.setProdCreUid(ShiroUtils.getUserId());
      dataModel.setProdIsDel((byte) 0);
      dataModel.setProdSta(1);
      dataList.add(dataModel);
    }
    return prodOrdService.saveEdit(removeProdOrds, dataList);
  }

  /**
   * 检测根据项目号检测数量
   *
   * @param num
   * @param prodProCod
   * @return
   */
  @ResponseBody
  @PostMapping("/checkNum")
  @RequiresPermissions("pro:release:edit")
  public JsonResult checkNum(Integer num, String prodProCod) {
    return prodOrdService.checkNum(num, prodProCod);
  }
  /**
   * 获取已存在的生产令列表
   *
   * @param proCode 项目号
   * @author 徐一贺
   * @date 2021/2/21 11:09
   */
  @ResponseBody
  @PostMapping("/loadAlreadyExistsProdList")
  public JsonResult loadAlreadyExistsProdList(String proCode) {
    return success().setData(prodOrdService.loadAlreadyExistsProdList(proCode));
  }

  /**
   * downloadProjectFile 请填写描述
   *
   * @param id 文件主键
   * @param httpServletResponse 下载相应体
   * @author 徐一贺
   * @date 2021/1/14 12:48
   */
  @GetMapping("/downloadProjectFile/{id}")
  public void downloadProjectFile(
      @PathVariable("id") Integer id, HttpServletResponse httpServletResponse) {
    try {
      VwPreEnquiryFile vwPreEnquiryFile = prodOrdService.getVwPreEnquiryFileById(id);
      VwProject vwProject = prodOrdService.getVwProjectByFileId(id);
      String filename = vwPreEnquiryFile.getUrl();
      filename = filename.replace("/files/", "/");
      FTPUtil ftpUtil = new FTPUtil();
      String localPath = uploadPath + filename.substring(filename.lastIndexOf("/"));
      File file = new File(localPath);
      file.deleteOnExit();
      ftpUtil.downloadFiles(filename, localPath);
      FileUtils.downloadFile(localPath, httpServletResponse);
      logService.saveLog(
          "生产任务管理-->生产令下达-->下载附件",
          "下载了项目编号为【"
              + vwProject.getProCode()
              + "】,项目名称为【"
              + vwProject.getProName()
              + "】，文件名称为【"
              + vwPreEnquiryFile.getFileName()
              + "】的附件。");
    } catch (Exception exception) {
      exception.printStackTrace();
    }
  }

  /**
   * gotoSplit 跳转到拆分生产令页面
   *
   * @param proId
   * @param model
   * @return java.lang.String
   * @author 徐一贺
   * @date 2021/1/14 16:31
   */
  @GetMapping("/gotoSplit/{proId}")
  @RequiresPermissions("pro:release:edit")
  public String gotoSplit(@PathVariable("proId") Integer proId, Model model) {
    model.addAttribute("proId", proId);
    return "prodTaskManager/split/page";
  }

  /**
   * 跳转到变更生产令页面
   *
   * @param prodId
   * @param model
   * @author 徐一贺
   */
  @GetMapping("/gotoChange/{prodId}")
  @RequiresPermissions("pro:release:edit")
  public String gotoChange(@PathVariable("prodId") Integer prodId, Model model) {
    ProdOrd prodOrd = prodOrdService.getProdOrdByPrimaryKey(prodId);
    model.addAttribute("prodOrd", prodOrd);
    model.addAttribute(
        "proId", prodOrdService.getVwProjectByProCode(prodOrd.getProdProCod()).getProId());
    return "prodTaskManager/change/page";
  }
  /**
   * gotoSplit 跳转到生产令编辑页面
   *
   * @param id
   * @param model
   * @return java.lang.String
   * @author 徐一贺
   * @date 2021/1/14 19:25
   */
  @GetMapping("/gotoEdit/{id}/{proId}")
  @RequiresPermissions("pro:release:edit")
  public String gotoEdit(
      @PathVariable("id") Integer id, @PathVariable("proId") Integer proId, Model model) {
    ProdOrd prodOrd = prodOrdService.getProdOrdByPrimaryKey(id);
    model.addAttribute("prodOrd", prodOrd);
    model.addAttribute("proId", proId);
    return "prodTaskManager/edit/page";
  }

  /**
   * removeProdOrd 删除生产令
   *
   * @param prodId 生产令主键
   * @return com.zw.mes.common.JsonResult
   * @author 徐一贺
   * @date 2021/1/15 9:56
   */
  @ResponseBody
  @PostMapping("/removeProdOrd")
  @RequiresPermissions("pro:release:del")
  public JsonResult removeProdOrd(Integer prodId) {
    return prodOrdService.removeProdOrd(prodId);
  }
  /**
   * submitProdOrd 提交生产令
   *
   * @param id 生产令主键
   * @return com.zw.mes.common.JsonResult
   * @author 徐一贺
   * @date 2021/1/15 10:24
   */
  @ResponseBody
  @PostMapping("/submitProdOrd")
  @RequiresPermissions("pro:release:commit")
  public JsonResult submitProdOrd(String id) {
    return prodOrdService.submitProdOrd(id);
  }

  /**
   * 恢复生产令生产状态为正常
   *
   * @param prodId
   * @return
   */
  @ResponseBody
  @PostMapping("/cancelStopProd")
  @RequiresPermissions("pro:release:end")
  public JsonResult cancelStopProd(Integer prodId) {
    return prodOrdService.cancelStopProd(prodId);
  }

  /**
   * saveSplit 保存拆分结果
   *
   * @param proId 项目主键
   * @param prodOrdStr 拆分的生产令数据
   * @return com.zw.mes.common.JsonResult
   * @author 徐一贺
   * @date 2021/1/14 16:57
   */
  @ResponseBody
  @PostMapping("/saveSplit")
  @RequiresPermissions("pro:release:commit")
  public JsonResult saveSplit(Integer proId, String prodOrdStr) {
    Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
    List<ProdOrd> prodOrds = gson.fromJson(prodOrdStr, new TypeToken<List<ProdOrd>>() {}.getType());
    for (int i = 0; i < prodOrds.size(); i++) {
      prodOrds.get(i).setProdCreUid(ShiroUtils.getUserId());
      prodOrds.get(i).setProdIsDel((byte) 0);
      prodOrds.get(i).setProdSta(1);
    }
    return prodOrdService.saveSplit(proId, prodOrds);
  }

  /**
   * saveProdOrdUpdate 更新生产令信息
   *
   * @param prodOrd 生产令信息
   * @return com.zw.mes.common.JsonResult
   * @author 徐一贺
   * @date 2021/1/14 20:37
   */
  @ResponseBody
  @PostMapping("/saveProdOrdUpdate")
  public JsonResult saveProdOrdUpdate(ProdOrd prodOrd) {
    return prodOrdService.saveProdOrdUpdate(prodOrd);
  }

  /**
   * 生产任务管理待处理项目数提示
   *
   * @return
   */
  @ResponseBody
  @PostMapping("/getProdTaskManPenItemPromptNum")
  public JsonResult getProdTaskManPenItemPromptNum() {
    return prodOrdService.getProdTaskManPenItemPromptNum();
  }

  /**
   * 跳转到项目文件查询页面
   *
   * @return
   */
  @GetMapping("/proFileQuery")
  public String goToProFileQueryPage() {
    return "prodTaskManager/goToProFileQuery/page";
  }

  /**
   * 加载项目文件查询页项目列表
   *
   * @param param
   * @return
   */
  @ResponseBody
  @PostMapping("/loadProjectByAttachmentList")
  @RequiresPermissions("pro:fileQuery:view")
  public JsonResult loadProjectByAttachmentList(ProjectByAttachmentListModel param) {
    startPage();
    return jsonResult(prodOrdService.loadProjectByAttachmentList(param));
  }

  /**
   * 根据条件查询销售系统的询价单附件、项目任务单附件、项目附件、技术协议这四种类型的文件列表
   *
   * @param param
   * @return
   */
  @ResponseBody
  @PostMapping("/loadProjectAttachmentList")
  @RequiresPermissions("pro:fileQuery:view")
  public JsonResult loadProjectAttachmentList(FileListModel param) {
    startPage();
    return jsonResult(prodOrdService.loadProjectAttachmentList(param));
  }

  /**
   * 文件打包下载
   *
   * @param param
   * @param response
   * @return
   * @throws Exception
   */
  @GetMapping("/downloadPackage")
  @RequiresPermissions("pro:fileQuery:download")
  public void downloadPackage(FileListModel param, HttpServletResponse response) throws Exception {
    String[] fileIdArray = param.getFileIds().split(",");
    String[] fileTypeArray = param.getFileTypes().split(",");
    List<FileListModel> requestList = new ArrayList<>();
    List files = new ArrayList();
    String logContent = "";
    for (int i = 0; i < fileIdArray.length; i++) {
      File file = null;
      if (Integer.valueOf(fileTypeArray[i]) == 1) {
        FileListModel fileListModel =
            prodOrdService.getInquirySheetAttachmentByFileId(Integer.valueOf(fileIdArray[i]));
        file = new File(fileListModel.getFilePath().replace("/", "\\"));
        logContent+="询价单附件，文件名：【"+fileListModel.getFileName()+"】，";
      }
      if (Integer.valueOf(fileTypeArray[i]) == 2) {
        //        file = new File("D:\\test.pdf");
      }
      if (Integer.valueOf(fileTypeArray[i]) == 3) {
        FileListModel fileListModel =
            prodOrdService.getProjectAttachmentByFileId(Integer.valueOf(fileIdArray[i]));
        file = new File(fileListModel.getFilePath().replace("/", "\\"));
        logContent+="项目附件，文件名：【"+fileListModel.getFileName()+"】，";
      }
      if (Integer.valueOf(fileTypeArray[i]) == 4) {
        FileListModel fileListModel =
            prodOrdService.getTechnicalAgreementAttachmentByFileId(Integer.valueOf(fileIdArray[i]));
        file = new File("e:\\sale\\upload\\" + fileListModel.getFilePath().substring(7).replace("/", "\\"));
        logContent+="技术协议，文件名：【"+fileListModel.getFileName()+"】，";
      }
      files.add(file);
    }
    logContent = logContent.substring(0,logContent.length()-1);
    if (files.size() > 0) {
      XYHFileUtils.downLoadFiles(files, response);
      logService.saveLog("项目文件查询-打包下载","打包下载了"+logContent+"。");
    }
  }

  /**
   * 下载单个文件
   *
   * @param fileId
   * @param fileType
   * @param response
   * @throws Exception
   */
  @GetMapping("/downloadFile/{fileId}/{fileType}")
  @RequiresPermissions("pro:fileQuery:download")
  public void downloadFile(
      @PathVariable("fileId") Integer fileId,
      @PathVariable("fileType") Integer fileType,
      HttpServletResponse response)
      throws Exception {
    File file = null;
    FileListModel fileListModel = null;
    String logTitle="";
    if (fileType == 1) {
      fileListModel = prodOrdService.getInquirySheetAttachmentByFileId(fileId);
      file = new File(fileListModel.getFilePath().replace("/", "\\"));
      logTitle="询价单附件,";
    }
    if (fileType == 2) {
      //        file = new File("D:\\test.pdf");
    }
    if (fileType == 3) {
      fileListModel = prodOrdService.getProjectAttachmentByFileId(fileId);
      file = new File(fileListModel.getFilePath().replace("/", "\\"));
      logTitle="项目附件,";
    }
    if (fileType == 4) {
      fileListModel = prodOrdService.getTechnicalAgreementAttachmentByFileId(fileId);
      file = new File("e:\\upload\\" + fileListModel.getFilePath().substring(7).replace("/", "\\"));
      logTitle="技术协议,";
    }
    logService.saveLog("项目文件查询-下载文件","下载了文件类型为【"+logTitle+"】，文件名为：【"+fileListModel.getFileName()+"】。");
    XYHFileUtils.download(file, fileListModel.getFileName(), response);
  }

  /**
   * 根据任务单id查看项目任务单页面
   *
   * @param proInvId
   * @param model
   * @return
   */
  @GetMapping("/viewProInvoice/{proInvId}")
  @RequiresPermissions("pro:fileQuery:download")
  public String viewProInvoice(@PathVariable("proInvId") Integer proInvId, Model model) {
    ProjectInvoiceModel proInvoice = prodOrdService.selectProInvoInfoById(proInvId);
    model.addAttribute("proInvInfo", proInvoice);
    VwProject project = prodOrdService.getVwProjectByPrimaryKey(proInvoice.getProId());
    logService.saveLog("项目文件查询-查看项目任务单","查看了项目号为【"+project.getProCode()+"】的项目任务单！");
    return "/prodTaskManager/goToProFileQuery/viewProInvoice";
  }
}
